package com.qyhl.webtv.module_news.news.normal;

import android.Manifest;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.tools.ScreenUtils;
import com.orhanobut.hawk.Hawk;
import com.qinanyu.bannerview.holder.SimpleHolder;
import com.qinanyu.bannerview.holder.SimpleHolderCreator;
import com.qinanyu.bannerview.listener.OnItemClickListener;
import com.qinanyu.bannerview.view.SimpleBannerView;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.basiclib.utils.glide.GlideCircleTransform;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.AppConfigConstant;
import com.qyhl.webtv.commonlib.entity.intergral.CoinBean;
import com.qyhl.webtv.commonlib.entity.news.AdvHomeBean;
import com.qyhl.webtv.commonlib.entity.news.AdvertiseBean;
import com.qyhl.webtv.commonlib.entity.news.GlobalNewsBean;
import com.qyhl.webtv.commonlib.entity.news.NormalNewsBean;
import com.qyhl.webtv.commonlib.item.ItemAdvCommon;
import com.qyhl.webtv.commonlib.item.ItemAdvGroup;
import com.qyhl.webtv.commonlib.item.ItemAdvLarge;
import com.qyhl.webtv.commonlib.item.ItemCatchNews;
import com.qyhl.webtv.commonlib.item.ItemCommonLarge;
import com.qyhl.webtv.commonlib.item.ItemCommonLeft;
import com.qyhl.webtv.commonlib.item.ItemCommonRight;
import com.qyhl.webtv.commonlib.item.ItemCommonThreePics;
import com.qyhl.webtv.commonlib.item.ItemGoodLife;
import com.qyhl.webtv.commonlib.item.ItemNoPicture;
import com.qyhl.webtv.commonlib.item.ItemOtherAdv;
import com.qyhl.webtv.commonlib.item.ItemPicture;
import com.qyhl.webtv.commonlib.item.ItemSmallVideo;
import com.qyhl.webtv.commonlib.item.ItemTitleNews;
import com.qyhl.webtv.commonlib.item.ItemTopNews;
import com.qyhl.webtv.commonlib.item.ItemTopNoPicture;
import com.qyhl.webtv.commonlib.item.ItemVideoLarge;
import com.qyhl.webtv.commonlib.item.ItemVideoLeft;
import com.qyhl.webtv.commonlib.item.ItemVideoRight;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.ItemSkipUtils;
import com.qyhl.webtv.commonlib.utils.MJavascriptInterface;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.cache.SpfManager;
import com.qyhl.webtv.commonlib.utils.coin.GoldCoinTimeView;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.share.ShareUtils;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBar;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBarOnClickListenerImpl;
import com.qyhl.webtv.commonlib.utils.view.video.normalvideo.QYVideoPlayer2;
import com.qyhl.webtv.module_news.utils.MyLoadingLayout;
import com.qyhl.webtv.module_news.utils.NewsConstant;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2017/11/17.
 * 普通新闻详情界面
 */

@Route(path = ARouterPathConstant.NORMAL_NEWS_ACTIVITY)
public class NormalNewsActivity extends BaseActivity implements NormalNewsContract.NormalView, BaseActivity.InputListener {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.publish_date)
    TextView publishDate;
    @BindView(R2.id.scan)
    TextView scan;
    @BindView(R2.id.top_adv)
    SimpleBannerView topAdv;
    @BindView(R2.id.summary)
    TextView summary;
    @BindView(R2.id.video_player)
    QYVideoPlayer2 videoPlayer;
    @BindView(R2.id.webview)
    WebView webview;
    @BindView(R2.id.web_layout)
    LinearLayout webLayout;
    @BindView(R2.id.praise_num)
    TextView praiseNum;
    @BindView(R2.id.praise_layout)
    RelativeLayout praiseLayout;
    @BindView(R2.id.share_txt)
    TextView shareTxt;
    @BindView(R2.id.share_wechat)
    TextView shareWechat;
    @BindView(R2.id.share_circle)
    TextView shareCircle;
    @BindView(R2.id.share_qq)
    TextView shareQq;
    @BindView(R2.id.extend_rv)
    RecyclerView extendRv;
    @BindView(R2.id.extend_layout)
    LinearLayout extendLayout;
    @BindView(R2.id.comment_lv)
    RecyclerView commentLv;
    @BindView(R2.id.more)
    TextView more;
    @BindView(R2.id.comment_layout)
    LinearLayout commentLayout;
    @BindView(R2.id.load_mask)
    MyLoadingLayout loadMask;
    @BindView(R2.id.bottombar)
    EditBar bottombar;
    @BindView(R2.id.scrollView)
    ScrollView scrollView;
    @BindView(R2.id.comment_mask)
    LoadingLayout commentMask;
    @BindView(R2.id.toolbar)
    Toolbar toolbar;
    @BindView(R2.id.origin_writer)
    TextView originWriter;
    @BindView(R2.id.coin_time_view)
    GoldCoinTimeView coinTimeView;
    @BindView(R2.id.coin_layout)
    CardView coinLayout;
    @BindView(R2.id.coin_login_tips)
    ImageView coinLoginTips;
    @BindView(R2.id.bottom_adv_layout)
    RelativeLayout bottomAdvLayout;
    @BindView(R2.id.bottom_adv_other)
    RelativeLayout otherbottomAdv;
    @BindView(R2.id.bottom_adv)
    SimpleBannerView bottomAdv;

    private boolean bottombarEnable = true;
    private boolean collectEnable = true;
    /*
     * 评论数据
     */
    private List<NormalNewsBean.ArticleComment> commentList;

    //转换后的拓展新闻数据
    private List<GlobalNewsBean> mDataList;

    private MultiItemTypeAdapter<GlobalNewsBean> mAdapter;
    private NormalNewsPresenter mPresenter;
    private CommonAdapter<NormalNewsBean.ArticleComment> commentAdapter;
    private DownloadCompleteReceiver receiver;

    //新闻id
    String newsId;

    private NormalNewsBean mBean;
    private int follows = 0;
    private static final float MIN_ALPHA = 0.0f;
    private RequestOptions options;

    private LoadingDialog.Builder builder;

    private boolean isLimited = false;

    private boolean isFirst = true;

    private boolean isCurFirst = true;

    private boolean isCollect;

    private boolean isPraise = false;

    private int collectNum;

    private int shareNum;

    private int commentNum;

//    private QuadNativeAd mQuadNativeAd;
//
//    private QuadNativeAd listQuadNativeAd;

    /**
     * 广告是否已经显示
     */
    private boolean isShowed = false;

    private boolean isItemShowed = false;

    private String advSwitch;

    private String integralSwitch;

    //储存地址
    private String phoneBasePath = "storage/emulated/0";
    //webView图片地址
    private String webViewBasePath = "file:///mnt/sdcard/";


    /**
     * webView待下载图片列表
     */
    private Map<String, String> mWebViewImageList = new HashMap<>();

    /*
     * 视频全屏参数
     */
    protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    private View customView;
    private FrameLayout fullscreenContainer;
    private WebChromeClient.CustomViewCallback customViewCallback;
    private String commentContent;
    private WebView finishWebView;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setSupportActionBar(toolbar);

    }


    @Override
    protected int getContentView() {
        return R.layout.news_activity_news_normal;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new NormalNewsPresenter(this);
        advSwitch = CommonUtils.getInstance().getOtherAdv();
        integralSwitch = CommonUtils.getInstance().getIntergralSwitch();
        newsId = getIntent().getStringExtra("id");
        initView();
        //统计
        mPresenter.count(newsId);
        //获取详情
        mPresenter.getDetail(newsId);
    }

    @Override
    protected void setListener() {
        setListeners();

    }

    /**
     * 初始化
     */
    private void initView() {
        extendRv.setFocusable(false);
        if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        addInputListener(this);
        loadMask.setStatus(LoadingLayout.Loading);
        mDataList = new ArrayList<>();
        commentList = new ArrayList<>();


        builder = new LoadingDialog.Builder(NormalNewsActivity.this);
        builder.setTitle("请稍等...");
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);

        //glide配置
        options = new RequestOptions()
                .centerCrop()
                .transform(new GlideCircleTransform(this))
                .placeholder(R.drawable.comment_head_default)
                .error(R.drawable.comment_head_default);

        //设置布局管理器
        extendRv.setLayoutManager(new LinearLayoutManager(this));
        DividerItemDecoration divider2 = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider2.setDrawable(ContextCompat.getDrawable(this, R.drawable.news_item_listview_divider));
        extendRv.addItemDecoration(divider2);

        //配置适配器
        mAdapter = new MultiItemTypeAdapter<GlobalNewsBean>(this, mDataList);
        mAdapter.addItemViewDelegate(new ItemAdvCommon(this));
        mAdapter.addItemViewDelegate(new ItemAdvGroup(this));
        mAdapter.addItemViewDelegate(new ItemAdvLarge(this));
        mAdapter.addItemViewDelegate(new ItemCatchNews(this));
        mAdapter.addItemViewDelegate(new ItemCommonLarge(this));
        mAdapter.addItemViewDelegate(new ItemCommonRight(this));
        mAdapter.addItemViewDelegate(new ItemCommonLeft(this));
        mAdapter.addItemViewDelegate(new ItemGoodLife(this));
        mAdapter.addItemViewDelegate(new ItemNoPicture(this));
        mAdapter.addItemViewDelegate(new ItemPicture(this));
        mAdapter.addItemViewDelegate(new ItemTitleNews(this));
        mAdapter.addItemViewDelegate(new ItemTopNews(this));
        mAdapter.addItemViewDelegate(new ItemTopNoPicture(this));
        mAdapter.addItemViewDelegate(new ItemVideoLarge(this));
        mAdapter.addItemViewDelegate(new ItemVideoLeft(this));
        mAdapter.addItemViewDelegate(new ItemVideoRight(this));
        mAdapter.addItemViewDelegate(new ItemSmallVideo(this));
        mAdapter.addItemViewDelegate(new ItemCommonThreePics(this));
        mAdapter.addItemViewDelegate(new ItemOtherAdv(NormalNewsActivity.this));

        extendRv.setAdapter(mAdapter);

        videoPlayer.setVisibility(View.GONE);


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        commentLv.setLayoutManager(linearLayoutManager);
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.news_recycleview_divider2));
        commentLv.addItemDecoration(divider);
        //评论
        commentLv.setAdapter(commentAdapter = new CommonAdapter<NormalNewsBean.ArticleComment>(this, R.layout.news_item_comment, commentList) {
            @Override
            protected void convert(ViewHolder holder, NormalNewsBean.ArticleComment item, int position) {
                holder.setText(R.id.nickName, item.getCommentuser());
                holder.setText(R.id.content, item.getContent());
                holder.setText(R.id.publish_date, DateUtils.mTranslateDate(item.getAddtime()));
                ImageView headIcon = holder.getView(R.id.head_icon);

                Glide.with(getApplicationContext())
                        .load(item.getLogo())
                        .apply(options)
                        .into(headIcon);
            }
        });

        bottombar.setBackground(R.color.white).hidePraise(false);

        if (advSwitch.equals("1")) {
            bottomAdvLayout.setVisibility(View.VISIBLE);
        } else {
            bottomAdvLayout.setVisibility(View.GONE);
        }
    }


    /**
     * 设置监听
     */
    private void setListeners() {


        coinTimeView.setOnClickListener(v -> RouterManager.router(ARouterPathConstant.ANTIC));
        //重新获取
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            //获取详情
            mPresenter.getDetail(newsId);
        });

        //重新获取评论
        commentMask.setOnReloadListener(v -> mPresenter.getComment(newsId));

        //评论栏
        bottombar.setEditBarOnClickListener(new EditBarOnClickListenerImpl() {
            @Override
            public void onSend() {
                if (bottombarEnable) {
                    bottombarEnable = false;
                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                commentContent = bottombar.getContent();
                                if (StringUtils.isEmpty(commentContent)) {
                                    Toasty.normal(NormalNewsActivity.this, "评论内容不能为空！", Toast.LENGTH_SHORT).show();
                                    bottombarEnable = true;
                                } else {
                                    String nickName = CommonUtils.getInstance().getNickName();
                                    mPresenter.sendComment(mBean.getTitle(), mBean.getCatalogID(), "1", mBean.getID(), nickName, commentContent);
                                    bottombar.clearContent();
                                    hideInput();//隐藏软键盘
                                }
                            } else {
                                Toasty.normal(NormalNewsActivity.this, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                                RouterManager.routerLogin(NormalNewsActivity.this, 0);
                                bottombarEnable = true;
                            }
                        }

                        @Override
                        public void error(String s) {
                            bottombarEnable = true;
                        }
                    });
                }
            }

            @Override
            public void onShare() {
                toShare();
            }

            @Override
            public void onCollect(final boolean isCollect) {
                if (collectEnable) {
                    collectEnable = false;
                    builder.show();

                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                if (isCollect) {
                                    mPresenter.collect(newsId);
                                } else {
                                    mPresenter.cancelCollect(newsId);
                                }
                            } else {
                                builder.dismiss();
                                bottombar.setCollect(false);
                                RouterManager.routerLogin(NormalNewsActivity.this, 0);
                                collectEnable = true;
                            }
                        }

                        @Override
                        public void error(String s) {
                            collectEnable = true;
                        }
                    });

                }
            }

            @Override
            public void onComment() {

                Bundle bundle = new Bundle();
                bundle.putString("id", mBean.getID());
                bundle.putString("sectionId", mBean.getCatalogID());
                bundle.putString("title", mBean.getTitle());

                RouterManager.router(ARouterPathConstant.NEWS_COMMENT, bundle);

            }

            @Override
            public void doPraise(boolean isPraised) {
                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            if (isPraised) {
                                mPresenter.cancelLike(newsId);
                            } else {
                                mPresenter.like(newsId);
                            }
                        } else {
                            builder.dismiss();
                            bottombar.isPraise(false);
                            RouterManager.routerLogin(NormalNewsActivity.this, 0);
                        }
                    }

                    @Override
                    public void error(String s) {

                    }
                });
            }
        });

        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                GlobalNewsBean bean = mDataList.get(position);
                ItemSkipUtils.getInstance().itemSkip(bean, NormalNewsActivity.this, view);
                if (CommonUtils.getInstance().getHasHistory()) {
                    //设置已读，保存记录于本地
                    Map<String, String> historyMap;
                    if (Hawk.contains("readHistory")) {
                        historyMap = CommonUtils.getInstance().getReadHistory();
                    } else {
                        historyMap = new HashMap<>();
                    }
                    historyMap.put(bean.getNewsId(), DateUtils.getCurrentTime());
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.READ_HISTORY, historyMap);
                    Hawk.put("readHistory", historyMap);
                    mAdapter.notifyItemChanged(position);
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        shareCircle.setOnClickListener(v -> MPermissionUtils.requestPermissionsResult(NormalNewsActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                ShareUtils.getInstance().goSingleShare("Circle", newsId, 1, mBean.getSummary(), mBean.getTitle(), mBean.getLogo(), NormalNewsActivity.this);
            }

            @Override
            public void onPermissionDenied() {
                MPermissionUtils.showTipsDialog(NormalNewsActivity.this);
            }
        }));

        shareQq.setOnClickListener(v -> MPermissionUtils.requestPermissionsResult(NormalNewsActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                ShareUtils.getInstance().goSingleShare("QQ", newsId, 1, mBean.getSummary(), mBean.getTitle(), mBean.getLogo(), NormalNewsActivity.this);
            }

            @Override
            public void onPermissionDenied() {
                MPermissionUtils.showTipsDialog(NormalNewsActivity.this);
            }
        }));

        shareWechat.setOnClickListener(v -> MPermissionUtils.requestPermissionsResult(NormalNewsActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                ShareUtils.getInstance().goSingleShare("WeiXin", newsId, 1, mBean.getSummary(), mBean.getTitle(), mBean.getLogo(), NormalNewsActivity.this);
            }

            @Override
            public void onPermissionDenied() {
                MPermissionUtils.showTipsDialog(NormalNewsActivity.this);
            }
        }));

        //点赞监听
        praiseLayout.setOnClickListener(v -> {
            if (Hawk.contains(newsId)) {
                mPresenter.cancelLike(newsId);
            } else {
                mPresenter.like(newsId);
            }
        });

        //更多跟帖
        more.setOnClickListener(v -> {

            Bundle bundle = new Bundle();
            bundle.putString("id", mBean.getID());
            bundle.putString("sectionId", mBean.getCatalogID());
            bundle.putString("title", mBean.getTitle());

            RouterManager.router(ARouterPathConstant.NEWS_COMMENT, bundle);

        });

        builder.getmDialog().setOnDismissListener(dialog -> {
//                OkHttpUtils.getInstance().cancelTag(NormalNewsActivity.this);
        });

        final Rect scrollBounds = new Rect();
        scrollView.getHitRect(scrollBounds);

        loadMask.setTouchEventListener(new MyLoadingLayout.TouchEventListener() {
            @Override
            public void moveAction() {
                if (integralSwitch.equals("1")) {
                    if (!isLimited && (Hawk.contains("login") || isFirst || isCurFirst)) {
                        coinTimeView.beginTime();
                    }

//                    if (bottomAdv.getLocalVisibleRect(scrollBounds) && !isShowed && mQuadNativeAd != null) {
//                        try {
//                            isShowed = true;
//                            mQuadNativeAd.onAdShowed(bottomAdv);
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }

//                    if (listQuadNativeAd != null && mDataList.size() > 2) {
//                        final RelativeLayout item = (RelativeLayout) extendLv.getChildAt(2);
//                        if (item != null && item.getLocalVisibleRect(scrollBounds) && !isItemShowed) {
//                            try {
//                                isItemShowed = true;
//                                listQuadNativeAd.onAdShowed(extendLv);
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }
                }

            }
        });

        if (integralSwitch.equals("1")) {
            coinLayout.setVisibility(View.VISIBLE);
            coinTimeView.setOnTimeoutListener(new GoldCoinTimeView.OnTimeoutListener() {
                @Override
                public void timeout() {
                    if (Hawk.contains("login")) {
                        String userName = CommonUtils.getInstance().getUserName();
                        mPresenter.getCoin(userName);
                    } else if (isFirst) {
                        coinLoginTips.setVisibility(View.GONE);
                        isFirst = false;
                        isCurFirst = false;
                        coinTimeView.stopTime();
                        coinTimeView.resetMax();
                    } else {
                        coinTimeView.stopTime();
                        isCurFirst = false;
                        coinTimeView.resetMax();
                    }

                }

                @Override
                public void limit() {
                    coinTimeView.stopTime();
                    isLimited = true;
                }
            });
        } else {
            coinLayout.setVisibility(View.GONE);
        }


    }

    /**
     * 评论列表
     *
     * @param list 评论数据
     */
    @Override
    public void commentSuccess(List<NormalNewsBean.ArticleComment> list) {
        commentMask.setStatus(LoadingLayout.Success);
        commentLayout.setVisibility(View.VISIBLE);
        if (list.size() > 0) {
            commentList.clear();
            commentList.addAll(list);
            commentAdapter.notifyDataSetChanged();
        } else {
            commentError(1, "暂无任何评论！");
        }
    }


    /**
     * 评论获取金币
     */
    private void getCommentCoin() {

        mPresenter.getCommentCoin("gainCoin", "4");
    }

    @Override
    public void getCommentCoinSuccess(CoinBean coinBean) {
        Toasty.normal(NormalNewsActivity.this, "成功评论，获得" + coinBean.getCoin() + "金币！").show();
    }

    @Override
    public void getCommentCoinFailure(String msg) {
        Log.i("coin_error", msg);
    }


    /**
     * 评论列表未取到
     *
     * @param msg 提示语
     */
    @Override
    public void commentError(int code, String msg) {
        commentLayout.setVisibility(View.VISIBLE);
        if (code == 0) {
            commentMask.setErrorImage(R.drawable.error_content);
            commentMask.setErrorText(msg);
            commentMask.setStatus(LoadingLayout.Error);
        } else if (code == 1) {
            commentMask.setEmptyImage(R.drawable.empty_comment);
            commentMask.setEmptyText(msg);
            commentMask.setStatus(LoadingLayout.Empty);
        } else {
            commentLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 设置详情
     *
     * @param bean 详情数据
     */
    @Override
    public void setDetail(NormalNewsBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        mBean = bean;
        //四川融媒统计
        if (CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) {
            StatisticsMainInit.newsInfoVisit(CommonUtils.getInstance().getUserName(), mBean.getID(), mBean.getTitle(), mBean.getReferName(), "0");
        }
        //设置标题
        if (StringUtils.isNotEmpty(mBean.getTitle())) {
            title.setVisibility(View.VISIBLE);
            title.setText(mBean.getTitle());
        } else {
            title.setVisibility(View.GONE);
        }
        //设置作者和来源
        if (StringUtils.isEmpty(mBean.getReferName())) {
            originWriter.setText(mBean.getWriter());
        } else {
            originWriter.setText(mBean.getReferName() + "\t\t\t" + mBean.getWriter());
        }
        //设置发布时间
        publishDate.setText(DateUtils.detailDateTranslate(mBean.getPublishDate()));
        //设置浏览数

        //设置浏览数
        try {
            int minPlay = Integer.parseInt(CommonUtils.getInstance().getMinPlay());
            if (minPlay == 0) {
                scan.setVisibility(View.GONE);
            } else {
                //判断评论数是否大于最少浏览数
                if (StringUtils.isEmpty(mBean.getHitCount())) {
                    scan.setVisibility(View.GONE);
                } else if (Integer.parseInt(mBean.getHitCount()) >=
                        minPlay) {
                    scan.setText(StringUtils.transformNum(mBean.getHitCount()));
                    scan.setVisibility(View.VISIBLE);
                } else {
                    scan.setVisibility(View.GONE);
                }
            }

        } catch (Exception e) {
            scan.setVisibility(View.GONE);
        }

        //设置摘要
        if (StringUtils.isNotEmpty(mBean.getSummary())) {
            summary.setVisibility(View.VISIBLE);
            summary.setText(mBean.getSummary());
        } else {
            summary.setVisibility(View.GONE);
        }


        //是否收藏
        isCollect = StringUtils.isNotEmpty(mBean.getIscollect()) && "1".equals(mBean.getIscollect());
        bottombar.setCollect(isCollect);

        collectNum = bean.getCollectCount();
        bottombar.setCollectNum(collectNum);

        shareNum = StringUtils.isEmpty(bean.getShareCount()) ? 0 : Integer.parseInt(bean.getShareCount());
        bottombar.setShareNum(shareNum);

        commentNum = bean.getCounts();
        bottombar.setCommentNum(commentNum);

        //是否喜欢
        if (StringUtils.isEmpty(mBean.getGoodViewCount())) {
            follows = 0;
        } else {
            follows = Integer.parseInt(mBean.getGoodViewCount());
        }

        if (Hawk.contains(newsId)) {
            setLike();
        } else {
            resetLike();
        }

        initWebView();//初始化webview

        setExtend(mBean.getActiveArticle());//设置延伸新闻

        mPresenter.getAdv(mBean.getCatalogID());
        mPresenter.getComment(newsId);
    }


    /**
     * 分享
     */
    private void toShare() {
        MPermissionUtils.requestPermissionsResult(NormalNewsActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                MShareBoard shareBoard = new MShareBoard(NormalNewsActivity.this, newsId, mBean.getTitle(), mBean.getLogo(), mBean.getSummary(), CommonUtils.getInstance().getBannerId(), 1);
                shareBoard.setShareCallBack(new MShareBoard.ShareCallBack() {
                    @Override
                    public void callBack() {
                        shareNum++;
                        bottombar.setShareNum(shareNum);
                        mPresenter.shareCount(newsId);
                    }
                });
                shareBoard.showPopupWindow();
            }

            @Override
            public void onPermissionDenied() {
                MPermissionUtils.showTipsDialog(NormalNewsActivity.this);
            }
        });
    }


    /**
     * 初始化webview
     */
    private void initWebView() {
        WebSettings settings = webview.getSettings();
        if (CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 127) {
            settings.setMediaPlaybackRequiresUserGesture(false);
        }
        settings.setJavaScriptEnabled(true);
        settings.setDefaultTextEncodingName("utf-8");
        settings.setDomStorageEnabled(true);
        settings.setBlockNetworkImage(true);//是否阻塞加载网络图片  协议http or https
        settings.setUseWideViewPort(false);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(false);
        setFontSize(SpfManager.getInstance(this).getInt("fontSize", 2));
        String htmlString = analysisContent(mBean.getContent());
        webview.loadDataWithBaseURL(null, htmlString, "text/html", "utf-8", null);
        webview.addJavascriptInterface(new MJavascriptInterface(this, StringUtils.returnImageUrlsFromHtml(htmlString)), "imagelistener");
        webview.setWebViewClient(mWebViewClient);

        webview.setWebChromeClient(new WebChromeClient() {

            /*** 视频播放相关的方法 **/

            @Override
            public View getVideoLoadingProgressView() {
                FrameLayout frameLayout = new FrameLayout(NormalNewsActivity.this);
                frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                return frameLayout;
            }

            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {
                showCustomView(view, callback);
            }

            @Override
            public void onHideCustomView() {
                hideCustomView();
            }

        });

        removeWebViewJI(webview);

        webview.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                downloadBySystem(url, contentDisposition, mimetype);
                showToast("正在下载中...");
            }
        });

        if(receiver!=null){
            unregisterReceiver(receiver);
        }
        // 使用
        receiver = new DownloadCompleteReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        registerReceiver(receiver, intentFilter);

    }

    private void downloadBySystem(String url, String contentDisposition, String mimeType) {
        // 指定下载地址
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        // 允许媒体扫描，根据下载的文件类型被加入相册、音乐等媒体库
        request.allowScanningByMediaScanner();
        // 设置通知的显示类型，下载进行时和完成后显示通知
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        // 设置通知栏的标题，如果不设置，默认使用文件名
//        request.setTitle("This is title");
        // 设置通知栏的描述
//        request.setDescription("This is description");
        // 允许在计费流量下下载
        request.setAllowedOverMetered(false);
        // 允许该记录在下载管理界面可见
        request.setVisibleInDownloadsUi(false);
        // 允许漫游时下载
        request.setAllowedOverRoaming(true);
        // 允许下载的网路类型
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        // 设置下载文件保存的路径和文件名
        String fileName  = URLUtil.guessFileName(url, contentDisposition, mimeType);
        Log.d("fileName:{}", fileName);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
//        另外可选一下方法，自定义下载路径
//        request.setDestinationUri()
//        request.setDestinationInExternalFilesDir()
        final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        // 添加一个下载任务
        long downloadId = downloadManager.enqueue(request);
        Log.d("downloadId:{}", downloadId+"");
    }

    private class DownloadCompleteReceiver extends BroadcastReceiver
    {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("onReceive. intent:{}", intent != null ? intent.toUri(0) : null);
            if (intent != null) {
                if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
                    long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                    Log.d("downloadId:{}", downloadId+"");
                    DownloadManager downloadManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
                    String type = downloadManager.getMimeTypeForDownloadedFile(downloadId);
                    if (TextUtils.isEmpty(type)) {
                        type = "*/*";
                    }
                    Uri uri = downloadManager.getUriForDownloadedFile(downloadId);
                    if (uri != null) {
                        Intent handlerIntent = new Intent(Intent.ACTION_VIEW);
                        handlerIntent.setDataAndType(uri, type);
                        context.startActivity(handlerIntent);
                    }
                }
            }
        }
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("http:") || url.startsWith("https:")) {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return false;
            }

            return true;
        }


        @Override
        public void onPageFinished(WebView view, String url) {
            loadMask.setStatus(LoadingLayout.Success);
            loadMask.setReloadButtonText("点击重试~~");
//            index = 1;
            /*
             * 非wifi下不加载图片
             */
            if (NetUtil.isWifi(NormalNewsActivity.this)) {
                webview.getSettings().setBlockNetworkImage(false);
            } else {
                if (SpfManager.getInstance(NormalNewsActivity.this).getBoolean("noPicture", false)) {
                    webview.getSettings().setBlockNetworkImage(true);
                } else {
                    webview.getSettings().setBlockNetworkImage(false);
                }
            }

            //这个是一定要加上那个的,配合scrollView和WebView的height=wrap_content属性使用
            int w = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            int h = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            //重新测量
            webview.measure(w, h);

            addImageClickListener(view);

        }

        @JavascriptInterface
        public void addImageClickListener(WebView webView) {
            webView.loadUrl(
                    "javascript:(function(){"
                            + "  var objs = document.getElementsByTagName(\"img\"); "
                            + "  for(var i=0;i<objs.length;i++){"
                            + "     objs[i].onclick=function(){"
                            + "          window.imagelistener.openImage(this.src);  "
                            + "     }"
                            + "  }"
                            + "})()");
        }

    };


    /**
     * 视频播放全屏
     **/
    private void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (customView != null) {
            callback.onCustomViewHidden();
            return;
        }

        NormalNewsActivity.this.getWindow().getDecorView();

        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        fullscreenContainer = new FullscreenHolder(NormalNewsActivity.this);
        fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
        decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
        customView = view;
        setStatusBarVisibility(false);
        customViewCallback = callback;
        //设置横屏
        if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        //设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    }

    /**
     * 隐藏视频全屏
     */
    private void hideCustomView() {
        if (customView == null) {
            return;
        }

        setStatusBarVisibility(true);
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        decor.removeView(fullscreenContainer);
        fullscreenContainer = null;
        customView = null;
        customViewCallback.onCustomViewHidden();
        webview.setVisibility(View.VISIBLE);
        // 设置竖屏
        if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        // 取消全屏
        final WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setAttributes(attrs);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    }

    @Override
    public void showkeyboard() {

    }

    @Override
    public void hideKeyboard() {
        bottombar.changeStateDefault(this);
    }

    /**
     * 全屏容器界面
     */
    static class FullscreenHolder extends FrameLayout {

        public FullscreenHolder(Context ctx) {
            super(ctx);
            setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
        }

        @Override
        public boolean onTouchEvent(MotionEvent evt) {
            return true;
        }
    }

    private void setStatusBarVisibility(boolean visible) {
        int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }


    /**
     * 详情出错
     *
     * @param msg
     */
    @Override
    public void detailError(String msg) {
        loadMask.setNoNetworkText(msg);
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 无内容
     *
     * @param msg
     */
    @Override
    public void showEmpty(String msg) {
        loadMask.setEmptyText(msg);
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 收藏成功
     *
     * @param msg
     */
    @Override
    public void collectSuccess(String msg) {
        builder.dismiss();
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
        isCollect = true;
        bottombar.setCollect(isCollect);
        collectNum++;
        bottombar.setCollectNum(collectNum);
        collectEnable = true;
        //四川融媒统计
        if ((CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) && mBean != null) {
            StatisticsMainInit.newsInfoCollect(CommonUtils.getInstance().getUserName(), mBean.getID(), mBean.getTitle(), "3");
        }
    }

    /**
     * 收藏失败
     *
     * @param msg 提示语
     */
    @Override
    public void collectError(String msg) {
        builder.dismiss();
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
        collectEnable = true;
    }

    /**
     * 取消收藏成功
     */
    @Override
    public void cancelCollectSuccess() {
        builder.dismiss();
        isCollect = false;
        bottombar.setCollect(isCollect);
        collectNum--;
        bottombar.setCollectNum(collectNum);
        BusFactory.getBus().post(new Event.CollectMessage(false));
        collectEnable = true;
    }

    /**
     * 取消收藏失败
     *
     * @param msg 提示语
     */
    @Override
    public void cancelCollectError(String msg) {
        builder.dismiss();
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
        collectEnable = true;
    }

    /**
     * 点赞成功
     */
    @Override
    public void likeSuccess() {
        follows++;
        Hawk.put(newsId, 0);
        setLike();
        //四川融媒统计
        if ((CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) && mBean != null) {
            StatisticsMainInit.thumbsUpLog(CommonUtils.getInstance().getUserName(), mBean.getID(), mBean.getTitle(), 1);
        }
    }

    /**
     * 点赞失败
     *
     * @param msg 提示语
     */
    @Override
    public void likeError(String msg) {
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 取消点赞成功
     */
    @Override
    public void cancelLikeSuccess() {
        follows--;
        Hawk.delete(newsId);
        resetLike();
        //四川融媒统计
        if ((CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) && mBean != null) {
            StatisticsMainInit.thumbsUpLog(CommonUtils.getInstance().getUserName(), mBean.getID(), mBean.getTitle(), 2);
        }
    }

    /**
     * 取消点赞失败
     *
     * @param msg 提示语
     */
    @Override
    public void cancelLikeError(String msg) {
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();


    }

    /**
     * 评论成功
     *
     * @param msg 提示语
     */
    @Override
    public void sendSuccess(String msg) {
        int commentRule = Integer.parseInt(CommonUtils.getInstance().getCommentRule());
        if (commentRule == 0) {
            Toasty.normal(this, "评论成功！").show();
            mPresenter.getComment(newsId);
        } else {
            Toasty.normal(this, "评论成功，等待审核！").show();
        }
        bottombar.changeStateDefault(this);
        bottombarEnable = true;
        String integralSwitch = CommonUtils.getInstance().getIntergralSwitch();
        if (integralSwitch.equals("1")) {
            getCommentCoin();
        }

        //四川融媒统计
        if ((CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) && mBean != null) {
            StatisticsMainInit.commentaryLog(CommonUtils.getInstance().getUserName(), mBean.getID(), mBean.getTitle(), commentContent);
        }
    }


    /**
     * 评论失败
     *
     * @param msg 提示语
     */
    @Override
    public void sendError(String msg) {
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
        bottombarEnable = true;
    }

    /**
     * 设置广告
     *
     * @param beanList 广告数据
     */
    @Override
    public void setAdv(List<AdvHomeBean> beanList) {
        final List<AdvertiseBean> topList = new ArrayList<>();
        final List<AdvertiseBean> bottomList = new ArrayList<>();
        for (int i = 0; i < beanList.size(); i++) {
            if ("-1".equals(beanList.get(i).getPosition())) {
                topList.addAll(beanList.get(i).getAdvertise());
            } else {
                bottomList.addAll(beanList.get(i).getAdvertise());
            }
        }
        //当广告只为一张时，设置不能滚动
        if (topList.size() == 1) {
            topAdv.setCanLoop(false);
        } else {
            topAdv.setCanLoop(true);
        }

        if (bottomList.size() == 1) {
            bottomAdv.setCanLoop(false);
        } else {
            bottomAdv.setCanLoop(true);
        }

        if (topList.size() > 0) {
            topAdv.setVisibility(View.VISIBLE);
            topAdv.setPages(new SimpleHolderCreator() {
                @Override
                public Object createHolder() {
                    return new AdvsImageHolderView();
                }
            }, topList)
                    .startTurning(4000)
                    .setPointViewVisible(false)
                    .canTouchScroll(false)
                    .setPageTransformer(new ViewPager.PageTransformer() {
                        @Override
                        public void transformPage(View page, float position) {
//                        if (position >= -1 && position <= 1) {
//                            page.setPivotX(position < 0 ? page.getWidth() : 0);//设置要旋转的Y轴的位置
//                            page.setRotationY(90 * position);//开始设置属性动画值
//                        }
                            int pageWidth = page.getWidth();    //得到view宽

                            if (position < -1) { // [-Infinity,-1)
                                // This page is way off-screen to the left. 出了左边屏幕
                                page.setAlpha(0);

                            } else if (position <= 1) { // [-1,1]
                                if (position < 0) {
                                    //消失的页面
                                    page.setTranslationX(-pageWidth * position);  //阻止消失页面的滑动
                                } else {
                                    //出现的页面
                                    page.setTranslationX(pageWidth);        //直接设置出现的页面到底
                                    page.setTranslationX(-pageWidth * position);  //阻止出现页面的滑动
                                }
                                // Fade the page relative to its size.
                                float alphaFactor = Math.max(MIN_ALPHA, 1 - Math.abs(position));
                                //透明度改变Log
                                page.setAlpha(alphaFactor);
                            } else { // (1,+Infinity]
                                // This page is way off-screen to the right.    出了右边屏幕
                                page.setAlpha(0);
                            }
                        }
                    })
                    .hideBannerText(true);
            topAdv.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    advSkip(topList.get(position));
                }
            });
        } else {
            topAdv.setVisibility(View.GONE);
        }

        if (bottomList.size() > 0) {
            bottomAdv.setVisibility(View.VISIBLE);
            otherbottomAdv.setVisibility(View.GONE);
            bottomAdv.setPages(new SimpleHolderCreator() {
                @Override
                public Object createHolder() {
                    return new AdvsImageHolderView();
                }
            }, bottomList)
                    .startTurning(4000)
                    .setPointViewVisible(false)
                    .canTouchScroll(false)
                    .setPageTransformer(new ViewPager.PageTransformer() {
                        @Override
                        public void transformPage(View page, float position) {
//                        if (position >= -1 && position <= 1) {
//                            page.setPivotX(position < 0 ? page.getWidth() : 0);//设置要旋转的Y轴的位置
//                            page.setRotationY(90 * position);//开始设置属性动画值
//                        }
                            int pageWidth = page.getWidth();    //得到view宽

                            if (position < -1) { // [-Infinity,-1)
                                // This page is way off-screen to the left. 出了左边屏幕
                                page.setAlpha(0);

                            } else if (position <= 1) { // [-1,1]
                                if (position < 0) {
                                    //消失的页面
                                    page.setTranslationX(-pageWidth * position);  //阻止消失页面的滑动
                                } else {
                                    //出现的页面
                                    page.setTranslationX(pageWidth);        //直接设置出现的页面到底
                                    page.setTranslationX(-pageWidth * position);  //阻止出现页面的滑动
                                }
                                // Fade the page relative to its size.
                                float alphaFactor = Math.max(MIN_ALPHA, 1 - Math.abs(position));
                                //透明度改变Log
                                page.setAlpha(alphaFactor);
                            } else { // (1,+Infinity]
                                // This page is way off-screen to the right.    出了右边屏幕
                                page.setAlpha(0);
                            }
                        }
                    })
                    .hideBannerText(true);
            bottomAdv.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    Bundle bundle = new Bundle();
                    bundle.putString("title", bottomList.get(position).getTitle());
                    bundle.putString("id", bottomList.get(position).getId() + "");
                    bundle.putString("url", bottomList.get(position).getLink());
                    RouterManager.router(ARouterPathConstant.ADV, bundle);
                }
            });
        } else {
            bottomAdv.setVisibility(View.GONE);
//            //加载广告
//            loadExpressAd();
        }


    }

    private void advSkip(AdvertiseBean advertiseBean) {
        if (StringUtils.isEmpty(advertiseBean.getLink())) {
            switch (advertiseBean.getLinkType()) {
                case "1": {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", advertiseBean.getLinkId());
                    RouterManager.router(ARouterPathConstant.TELE_VIDEO_ACTIVITY, bundle);
                }
                break;
                case "2": {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", advertiseBean.getLinkId());
                    RouterManager.router(ARouterPathConstant.SCOOP_DETAIL_ACTIVIT, bundle);
                }
                break;
                case "3":
                    switch (advertiseBean.getContentType()) {
                        case "1": {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", advertiseBean.getLinkId());
                            RouterManager.router(ARouterPathConstant.NORMAL_NEWS_ACTIVITY, bundle);
                        }
                        break;
                        case "2": {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", advertiseBean.getLinkId());
                            bundle.putString("section", advertiseBean.getCatalogID());
                            RouterManager.router(ARouterPathConstant.PICTURE_NEWS_ACTIVITY, bundle);
                        }
                        break;
                        case "3":
                            break;
                        case "4":
                            break;
                        case "5": {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", advertiseBean.getLinkId());
                            RouterManager.router(ARouterPathConstant.VIDEO_NEWS_ACTIVITY, bundle);
                        }
                        break;
                        case "8": {
//                            Router.build("room_act")
//                                    .with("roomId", Integer.parseInt(advertiseBean.getLinkId()))
//                                    .go(NormalNewsActivity.this);
                        }
                        break;
                        case "101": {
                            Bundle bundle = new Bundle();
                            bundle.putString("id", advertiseBean.getLinkId());
                            RouterManager.router(ARouterPathConstant.NEWS_CATCH, bundle);
                        }
                        break;
                        default:
                            break;
                    }
                    break;
                case "4": {
                    Bundle bundle = new Bundle();
                    bundle.putString("actId", advertiseBean.getLinkId());
                    RouterManager.router(ARouterPathConstant.ACT_DETAILS, bundle);
                    ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.ACTIVITY_DETAIL);
                }
                default:

                    break;

            }
        } else {
            Bundle bundle = new Bundle();
            bundle.putString("title", advertiseBean.getTitle());
            bundle.putString("id", advertiseBean.getId() + "");
            bundle.putString("url", advertiseBean.getLink());
            RouterManager.router(ARouterPathConstant.ADV, bundle);
        }

        ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.ADV);

    }


    //广告的viewholder
    class AdvsImageHolderView implements SimpleHolder<AdvertiseBean> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, AdvertiseBean data) {
            try {
                Glide.with(context.getApplicationContext())
                        .load(data.getImageUrl())
                        .into(imageView);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    /**
     * 取消广告
     */
    @Override
    public void advError() {
        topAdv.setVisibility(View.GONE);
        bottomAdv.setVisibility(View.GONE);
    }

    @Override
    public void cancelCollect() {
        builder.dismiss();
        collectEnable = true;
    }

    @Override
    public void getCoinSuccess(CoinBean bean) {
        coinTimeView.transformation(bean.getCoin() + "", 3);
        if (isLimited) {
            coinTimeView.setEnjoin(true);
            coinTimeView.setProgress(0);
        }
    }

    @Override
    public void getCoinFailure(String msg) {
        Log.i("coin", msg);
        coinTimeView.stopTime();
        coinTimeView.setEnjoin(true);
    }


    /**
     * 解析web内容
     */
    private String analysisContent(String content) {

        String videoCss = "<style type='text/css'>"//针对video标签的处理，去掉下载按钮,以及图片最大宽度
                + "img {"
                + "max-width: 100%; "
                + "}"
                + "video::-webkit-media-controls-enclosure {"
                + "overflow:hidden;"
                + "}"
                + "video::-webkit-media-controls-panel {"
                + "width: calc(100% + 32px);"
                + "}"
                // 这个方式兼容所有版本的谷歌浏览器
                + "audio::-webkit-media-controls {"
                + "overflow: hidden !important"
                + "}"
                + "audio::-webkit-media-controls-enclosure {"
                + "width: calc(100% + 32px);"
                + "margin-left: auto;"
                + "}"
                + "video{"
                + "max-width: 100%;"
                + "}"
                + "audio{"
                + "clear:both;"
                + "display:block;"
                + "margin:auto;"
                + "max-width: 100%;"
                + "}"
                + "</style>";
        content = "<html><head>" + videoCss + "</head><body>" + content + "</body></html>";
        if (content.indexOf("max-width") != -1) {
            content = content.replaceAll("max-width: \\d+px", "max-width: 100%");
            content = content.replaceAll("max-width:\\d+px", "max-width:100%");
        }

        if (content.indexOf("style=\"width:") != -1) {
            content = content.replaceAll("style=\"width: \\d+px;\"", "");
            content = content.replaceAll("style=\"width:\\d+px;\"", "");
        }
        return getNewContent(content);
    }


    //webview中的图片自适应大小
    private String getNewContent(String htmltext) {
        Document doc = Jsoup.parse(htmltext);
        Elements elements = doc.getElementsByTag("img");
        for (Element element : elements) {
            element.attr("style", "max-width:100% !important;max-height:auto !important");
        }
        return doc.toString();
    }

    /**
     * 显示视频
     *
     * @param url
     */
    private void setVideo(String url, String logo) {
        videoPlayer.setVisibility(View.VISIBLE);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) videoPlayer.getLayoutParams();
        params.height = (ScreenUtils.getScreenWidth(this) - 40) / 16 * 9;
        videoPlayer.setLayoutParams(params);

        ImageView imageView = new ImageView(this);


        Glide.with(this)
                .load(logo)
                .apply(new RequestOptions().error(R.drawable.cover_video_default))
                .into(imageView);
        videoPlayer.setThumbImageView(imageView);
        videoPlayer.setRotateViewAuto(false);
        videoPlayer.setLockLand(true);
        videoPlayer.setUp(mBean.getPlayerpath() == null ? "" : mBean.getPlayerpath(), true, "");
        videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                videoPlayer.startWindowFullscreen(NormalNewsActivity.this, true, true);
            }
        });
        videoPlayer.getBackButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (GSYVideoManager.backFromWindowFull(NormalNewsActivity.this)) {

                } else {
                    finish();
                }
            }
        });
    }

    //喜欢后
    private void setLike() {
        praiseLayout.setBackgroundResource(R.drawable.news_praise_bg_on);
        praiseNum.setTextColor(ContextCompat.getColor(this, R.color.white));
        Drawable drawable = getResources().getDrawable(R.drawable.praise_on);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());/// 这一步必须要做,否则不会显示.
        praiseNum.setCompoundDrawables(drawable, null, null, null);
        praiseNum.setText(follows + "");
        isPraise = true;
        bottombar.isPraise(true);
        bottombar.setPraiseNum(follows);

    }

    //喜欢前
    private void resetLike() {
        praiseLayout.setBackgroundResource(R.drawable.news_praise_bg_off);
        praiseNum.setTextColor(ContextCompat.getColor(this, R.color.global_black_lv1));
        Drawable drawable = getResources().getDrawable(R.drawable.praise_off);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());/// 这一步必须要做,否则不会显示.
        praiseNum.setCompoundDrawables(drawable, null, null, null);
        praiseNum.setText(follows + "");
        isPraise = false;
        bottombar.isPraise(false);
        bottombar.setPraiseNum(follows);
    }

    /**
     * 设置延伸阅读
     *
     * @param beanList
     */
    private void setExtend(List<NormalNewsBean.ActiveAiticle> beanList) {
        if (beanList != null && beanList.size() > 0) {
            int globalCommon = Integer.parseInt(CommonUtils.getInstance().getGlobalCommon());
            int globalVideo = Integer.parseInt(CommonUtils.getInstance().getGlobalVideo());
            for (int i = 0; i < beanList.size(); i++) {
                if ("1".equalsIgnoreCase(beanList.get(i).getType()) || "5".equalsIgnoreCase(beanList.get(i).getType())) {
                    beanList.get(i).setCommonStyle(globalCommon);
                    beanList.get(i).setVideoStyle(globalVideo);
                }
            }

            final List<GlobalNewsBean> indexList = new ArrayList<>();
            for (int i = 0; i < beanList.size(); i++) {
                NormalNewsBean.ActiveAiticle bean = beanList.get(i);
                boolean hasPicture = StringUtils.isPictureSuccess(bean.getLogo());
                String type = "", pOne = "", pTwo = "", pThree = "";
                int style = 0;
                switch (bean.getType()) {
                    case "1"://普通新闻
                        type = "1";
                        switch (bean.getPluralPicsFlag()) {
                            case 0:
                                style = bean.getCommonStyle();
                                break;
                            case 1://三图
                                hasPicture = false;
                                if (bean.getImagess().size() == 1) {
                                    hasPicture = true;
                                    pOne = bean.getImagess().get(0).getImageUrlString();
                                } else if (bean.getImagess().size() == 2) {
                                    pOne = bean.getImagess().get(0).getImageUrlString();
                                    pTwo = bean.getImagess().get(1).getImageUrlString();
                                    hasPicture = true;
                                } else if (bean.getImagess().size() >= 3) {
                                    pOne = bean.getImagess().get(0).getImageUrlString();
                                    pTwo = bean.getImagess().get(1).getImageUrlString();
                                    pThree = bean.getImagess().get(2).getImageUrlString();
                                    hasPicture = true;
                                } else {
                                    hasPicture = false;
                                }
                                style = 4;
                                break;
                            case 2:
                                style = 3;
                                break;
                            default:
                                style = bean.getCommonStyle();
                                break;
                        }
                        break;
                    case "2"://图片新闻
                        type = "2";
                        if (bean.getImagess().size() == 1) {
                            pOne = bean.getImagess().get(0).getImageUrlString();
                            hasPicture = true;
                        } else if (bean.getImagess().size() == 2) {
                            pOne = bean.getImagess().get(0).getImageUrlString();
                            pTwo = bean.getImagess().get(1).getImageUrlString();
                            hasPicture = true;
                        } else if (bean.getImagess().size() >= 3) {
                            pOne = bean.getImagess().get(0).getImageUrlString();
                            pTwo = bean.getImagess().get(1).getImageUrlString();
                            pThree = bean.getImagess().get(2).getImageUrlString();
                            hasPicture = true;
                        } else {
                            hasPicture = false;
                        }
                        break;
                    case "3"://直播
                        type = "9";
                        break;
                    case "4"://标题新闻
                        type = "8";
                        break;
                    case "5"://视频新闻
                        type = "3";
//                        style = bean.getVideoStyle();
                        style = 1;
                        break;
                    case "8"://互动直播
                        bean.setID(bean.getRoomId());//将roomId设置成通用Id
                        type = "5";
                        break;
                    case "101"://抓取新闻
                        type = "10";
                        break;
                    default:
                        break;
                }
                indexList.add(new GlobalNewsBean(bean.getTitle(), bean.getID(), bean.getRedirectURL(), bean.getLogo(), style, bean.getPublishDate(), type, Integer.parseInt(bean.getHitCount()), "", bean.getCatalogID(), hasPicture, pOne, pTwo, pThree, bean.getLivetype(), bean.getCommentCount()));
            }

            //更新数据源
            mDataList.clear();
            mDataList.addAll(indexList);
            mAdapter.notifyDataSetChanged();
//
        } else {
            extendLayout.setVisibility(View.GONE);
        }

    }

    /**
     * 设置webview字体大小
     */
    private void setFontSize(int position) {
        switch (position) {
            case 0:
                webview.getSettings().setTextZoom(50);
                break;
            case 1:
                webview.getSettings().setTextZoom(75);
                break;
            case 2:
                webview.getSettings().setTextZoom(100);
                break;
            case 3:
                webview.getSettings().setTextZoom(150);
                break;
            case 4:
                webview.getSettings().setTextZoom(200);
                break;
            default:
                break;
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (customView != null) {
                    hideCustomView();
                    return true;
                } else if (bottombar.getType() == EditBar.TYPE_SEND) {//判断是否是输入状态，是则返回初始状态，否则退出
                    bottombar.changeStateDefault(this);
                    return true;
                } else if (GSYVideoManager.backFromWindowFull(this)) {
                    return true;
                } else if (webview != null && webview.canGoBack()) {
                    webview.goBack();
                } else {
                    finish();
                }
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("普通新闻详情");
        MobclickAgent.onResume(this);
        if (videoPlayer != null) {
            videoPlayer.onVideoResume();
        }
        ActionLogUtils.getInstance().onResume(this, ActionConstant.NEWSDETAIL);
        if (integralSwitch.equals("1")) {
            coinTimeView.setRepeat(false);
            if (isLimited) {
                coinTimeView.setEnjoin(true);
                coinTimeView.setProgress(0);
            } else if (Hawk.contains("login")) {
                if (NewsConstant.curProgress != 0) {
                    coinTimeView.setProgress(NewsConstant.curProgress);
                }
                coinTimeView.beginTime();
            } else {
                isFirst = SpfManager.getInstance(this).getBoolean("isFirst", true);
                if (SpfManager.getInstance(this).getBoolean("isFirst", true)) {
                    coinLoginTips.setVisibility(View.VISIBLE);
                    SpfManager.getInstance(this).putBoolean("isFirst", false);
                    coinTimeView.beginTime();
                } else {
                    coinLoginTips.setVisibility(View.GONE);
                    coinTimeView.beginTime();
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (webview != null) {
//            webview.reload();
        }
        //baidu
        //umeng
        MobclickAgent.onPageEnd("普通新闻详情");
        MobclickAgent.onPause(this);
        if (videoPlayer != null) {
            videoPlayer.onVideoPause();
        }
        ActionLogUtils.getInstance().onPause(this, ActionConstant.NEWSDETAIL);
        if (Hawk.contains("login") && integralSwitch.equals("1")) {
            NewsConstant.curProgress = coinTimeView.getProgress();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
//        webview.reload();
        //四川融媒统计
        if ((CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) && mBean != null) {
            StatisticsMainInit.newsInfoVisit(CommonUtils.getInstance().getUserName(), mBean.getID(), mBean.getTitle(), mBean.getReferName(), "1");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webview != null) {
            webview.removeAllViews();
            webview.destroy();
        }
        if (videoPlayer != null) {
            videoPlayer.release();
        }
        if (Hawk.contains("login") && integralSwitch.equals("1")) {
            coinTimeView.stopTime();
        }

    }


    /**
     * eventBus 接收器
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.LoginMessage event) {
        if (event != null) {
            if (event.isLogin()) {//登录
                mPresenter.getDetail(newsId);
            } else {//注销
                mPresenter.getDetail(newsId);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void commentAdd(Event.commentAdd event) {
        if (event != null) {
            commentNum++;
            bottombar.setCommentNum(commentNum);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        } else if (item.getItemId() == R.id.more) {
            MShareBoard shareBoard = new MShareBoard(NormalNewsActivity.this, newsId, mBean.getTitle(), mBean.getLogo(), mBean.getSummary(), CommonUtils.getInstance().getBannerId(), 1, true, isCollect);
            shareBoard.setToolListener(new MShareBoard.ShareToolListener() {
                @Override
                public void collectChange(boolean isCollect) {
                    if (isCollect) {
                        mPresenter.cancelCollect(newsId);
                    } else {
                        mPresenter.collect(newsId);
                    }
                }

                @Override
                public void textSizeChange() {
                    int checkId;
                    switch (SpfManager.getInstance(NormalNewsActivity.this).getInt("fontSize", 2)) {
                        case 0:
                            checkId = R.id.textsize_lv1;
                            break;
                        case 1:
                            checkId = R.id.textsize_lv2;
                            break;
                        case 2:
                            checkId = R.id.textsize_lv3;
                            break;
                        case 3:
                            checkId = R.id.textsize_lv4;
                            break;
                        case 4:
                            checkId = R.id.textsize_lv5;
                            break;
                        default:
                            checkId = R.id.textsize_lv3;
                            break;
                    }
                    new OtherDialog.Builder(NormalNewsActivity.this)
                            .setContentView(R.layout.news_dialog_textsize_choice)
                            .setWidth(0.8f)
                            .setCanceledOnTouchOutside(true)
                            .setOnCheckedChangeListener(R.id.dialog_radioGroup, checkId, new OtherDialog.CheckedChangeListener() {
                                @Override
                                public void checkedChange(int position) {
                                    SpfManager.getInstance(NormalNewsActivity.this).putInt("fontSize", idToPosition(position));
                                    setFontSize(idToPosition(position));
                                }
                            })
                            .setDismissButton(R.id.dialog_cancel)
                            .show();
                }
            });
            shareBoard.showPopupWindow();
        }
        return super.onOptionsItemSelected(item);
    }

    private int idToPosition(int checkId) {
        int pos = 2;
        if (checkId == R.id.textsize_lv1) {
            pos = 0;
        } else if (checkId == R.id.textsize_lv2) {
            pos = 1;
        } else if (checkId == R.id.textsize_lv3) {
            pos = 2;
        } else if (checkId == R.id.textsize_lv4) {
            pos = 3;
        } else if (checkId == R.id.textsize_lv5) {
            pos = 4;
        }
        return pos;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.news_detail_mores, menu);
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
